package com.yc.ycpaimon.utils

import android.webkit.CookieManager
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import com.yc.jetpacklib.extension.ycLogE
import com.yc.ycpaimon.data.constant.Constants

/**
 * Creator: yc
 * Date: 2022/2/17 17:34
 * UseDes:
 */
object WebUtil {
    fun WebSettings.ycSettingInit() {
        mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        javaScriptEnabled = true
        loadWithOverviewMode = true
        domStorageEnabled = true
        blockNetworkImage = false
        useWideViewPort = true
    }

    fun createBbsWebClient(block: (bbsCookie: String) -> Unit) = object : WebViewClient() {
        override fun onPageFinished(view: WebView?, url: String?) {
            val cookieManager = CookieManager.getInstance()
            val cookies = cookieManager.getCookie(url)
            //当网页加载完毕时
            if (view?.progress == 100 && cookies != null && cookies.isNotEmpty()) {
                val cookieSplit = cookies.split(";")
                val cookieMap = mutableMapOf<String, String>()
                ycLogE(cookies)
                cookieSplit.forEach {
                    val cookie = it.trim().split("=")
                    cookieMap += cookie.first().trim() to cookie.last().trim()
                    if (cookie[0] == Constants.ACCOUNT_ID_NAME) {
                        block.invoke(cookie.first())
                    }
                }
            }
        }
    }
}